<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <title>画笔</title>
</head>
<style>
    html,body{

    }
    canvas{
        box-shadow: 2px 5px 10px #dde;
    }

    ul{
        margin:0;
        padding:0;
    }

    #utils{
        height:50px;
    }
    #utils li{
        display: inline-block;
        height:30px;
        width:80px;
        text-align: center;
        line-height: 30px;
        background-color: #99cd78;
        color:#fff;
        cursor: pointer;
        /*cursor: url(https://davidwalsh.name/demo/css-custom-cursor.ico) 20 20,auto;*/
    }
    #myCanvas{
        cursor: url('./img/pan.png') 5 40,pointer;
    }


</style>
<body>

<div id="utils">
    <ul>
        <ul style="margin-bottom: 10px;">
            <li>直线</li>
            <li>圆</li>
            <li>矩形</li>
            <li>多边形</li>
        </ul>
        <li onclick="downloadFile()">下载</li>
        <li onclick="clearAll()">
            清空
        </li>
        <li onclick="clearDraw()">
            橡皮擦
        </li>
        <li style="width:180px;font-size:12px" >
            <span onclick="paintBrush()">画笔</span>

            <select id="options" style="border: 0;cursor: pointer;outline: none">
                <option value="1">1px</option>
                <option value="2">2px</option>
                <option value="3">3px</option>
                <option value="4">4px</option>
                <option value="5">5px</option>
            </select>
            <span style="">自定义：</span><input id="enterNum" type="text" style="width: 30px;display: inline-block;
                border:0;outline: none" value="1">

<!--            <button onclick="paintBrush()" style="outline:none;height:20px;width:40px;border:0;background-color: #4dafdd;-->
<!--color: #fff;cursor:pointer;">确定</button>-->
        </li>
        <li style="width: 100px;">
            色板
            <input style="vertical-align: middle" id="selectColor" type="color" value="#2D9900"/>
        </li>
    </ul>
</div>
    <canvas id="myCanvas" height="600" width="800">

    </canvas>

</body>
</html>

<script>
    var body = document.body;
    var colorSel = document.getElementById('selectColor');
    var options = document.getElementById('options');
    var enterNum = document.getElementById('enterNum');
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    ctx.strokeStyle = colorSel.value;
    ctx.lineWidth = options.value;


    /**
     * 监听canvas宽高
     * */
    resize_canvas();
    function resize_canvas(){
        if (canvas.width  < window.innerWidth)
        {
            canvas.width  = window.innerWidth-50;
        }

        if (canvas.height < window.innerHeight)
        {
            canvas.height = window.innerHeight-150;
        }
    }

    var imageDl = canvas.toDataURL("image/png");

    colorSel.oninput = function () {
        console.log("selectColor"+colorSel.value);
        ctx.strokeStyle = colorSel.value;
        ctx.lineWidth = options.value;
        // ctx.globalCompositeOperation = 'false';
        paintBrush();
    };

    options.onchange = function () {
        // console.log("33")
        enterNum.value = options.value;
        paintBrush();
    };

    enterNum.onchange = function () {
        console.log("333");
        paintBrush();
    };

    /**
     * 画直线
     * */
    // function paintLine() {
    //     canvas.style = "cursor: url('./img/pan.png') 5 40,pointer;";
    //     ctx.strokeStyle = colorSel.value;
    //     ctx.lineWidth = enterNum.value;
    //     // ctx.globalCompositeOperation = 'false';
    //     mouseFun();
    // }

    function paintBrush(){//画笔
        canvas.style = "cursor: url('./img/pan.png') 5 40,pointer;";
        ctx.strokeStyle = colorSel.value;
        ctx.lineWidth = enterNum.value;
        // ctx.globalCompositeOperation = 'false';
        mouseFun();
    }
    function clearDraw() {//橡皮擦
        canvas.style = "cursor: url('./img/rubber.png') 10 40,pointer;";
        console.log("clear");
        ctx.strokeStyle = "#fff";
        ctx.lineWidth = enterNum.value;
        ctx.lineCap = 'round';//画笔的样式  圆形
        mouseFun();
    }

    /**
     * 清空画布
     */
    function clearAll() {
        ctx.clearRect(0,0,canvas.width,canvas.height);
    }

    function Draw(obj,setting){
        console.log(setting)
        this.obj=obj;
        this.type=setting.type||"stroke";
        this.color=setting.color||"#000";
        this.width=setting.width||"1";
    }
    Draw.prototype={
        init:function(){
            this.obj.strokeStyle=this.color;
            this.obj.fillStyle=this.color;
            this.obj.lineWidth=this.width;
        },
        rect:function(x,y,x1,y1){
            this.init();
            this.obj.beginPath();
            this.obj.rect(x,y,x1-x,y1-y);
            if(this.type=="stroke"){
                this.obj.stroke();
            }else if(this.type=="fill"){
                this.obj.fill();
            }
        },
        line:function(x,y,x1,y1){
            this.init();
            this.obj.beginPath();
            this.obj.moveTo(x,y);
            this.obj.lineTo(x1,y1);
            this.obj.stroke();
        },
        circle:function(x,y,x1,y1){
            this.init();
            var r=Math.sqrt(Math.pow(x-x1,2)+Math.pow(y-y1,2));
            this.obj.beginPath();
            this.obj.arc(x,y,r,0,2*Math.PI);
            if(this.type=="stroke"){
                this.obj.stroke();
            }else if(this.type=="fill"){
                this.obj.fill();
            }
        },
        poly:function(x,y,x1,y1,n){
            this.init();
            var obj=this.obj;
            var r=Math.sqrt(Math.pow(x-x1,2)+Math.pow(y-y1,2));;
            obj.save();
            obj.translate(x,y);
            obj.rotate(Math.PI/2);
            var nx=r*Math.cos(Math.PI/n);
            var ny=r*Math.sin(Math.PI/n);
            obj.beginPath();
            obj.lineCap="round";
            obj.moveTo(nx,ny);
            for(var i=0;i<=n;i++){
                obj.rotate(Math.PI*2/n);
                obj.lineTo(nx,-ny);
            }
            if(this.type=="stroke"){
                this.obj.stroke();
            }else if(this.type=="fill"){
                this.obj.fill();
            }
            obj.restore();
        },
        pen:function(x,y,x1,y1){
            this.init();
            this.obj.save();
            this.obj.lineCap="round";
            this.obj.lineTo(x1,y1);
            this.obj.stroke();
            this.obj.restore();
        },
        eraser:function(x,y,x1,y1){
            this.obj.lineCap="round";
            this.obj.clearRect(x1-5,y1-5,10,10);
        },
        cut:function(x,y,x1,y1){
            this.init();
            this.obj.save();
            this.obj.setLineDash([4,2]);
            this.obj.beginPath();
            this.obj.lineWidth=1;
            this.obj.rect(x,y,x1-x,y1-y);
            this.obj.stroke();
            this.obj.restore();
        }
    }


    var type = 'eraser', cutflag = true;
    var draw=new Draw(ctx,{type:'stroke',color:"#ff0",width:"2"});//实例化构造函数
    mouseFun();//初始化画笔
    function mouseFun(){
        canvas.onmousedown = function (e) {
            var event = e || window.event;
            var x = event.clientX - canvas.offsetLeft;
            var y = event.clientY - canvas.offsetTop;

            if(type=="pen"){
                ctx.beginPath();
                ctx.moveTo(x,y);
            }
            if(type=="eraser"){
                ctx.clearRect(x-5,y-5,10,10);
            }
            if(cutflag&&type=="cut"){
                if(arr.length!=0){
                    arr.splice(-1,1);
                }
            }

            // ctx.beginPath();
            // ctx.moveTo(x,y);

            /**
             * 自由画线
             * */
            canvas.onmousemove = function (el) {
                var ev = el || window.event;
                var w = ev.clientX - canvas.offsetLeft;
                var h = ev.clientY - canvas.offsetTop;

                // w=el.offsetX;
                // h=el.offsetY;

                if(type!="eraser"){
                    ctx.clearRect(0,0,width,height);
                    if(arr.length!=0){
                        ctx.putImageData(arr[arr.length-1],0,0,0,0,width,height);
                    }
                }
                if(cutflag&&type=="cut"){
                    if(iscut){
                        ctx.clearRect(lx,ly,lw-lx,lh-ly);
                    }
                    var nx=lx+(w-x);
                    var ny=ly+(h-y);
                    ctx.putImageData(cutdata,nx,ny);
                }else if(type=="poly"){
                    draw[type](x,y,w,h,2);
                }else{
                    console.log(type)
                    draw[type](x,y,w,h,10);
                }

                // ctx.lineTo(x,y);
                // ctx.closePath();
                // ctx.stroke();

            };

            body.onmouseup = function (e) {
                canvas.onmousemove=null;
                document.onmouseup=null;
                // canvas.onmousemove = {};
                //
                // imageDl = canvas.toDataURL("image/png");
            };

        }



    }







    /* base64转blob对象 */
    function dataURItoBlob(code) {
        var parts = code.split(';base64,');
        var contentType = parts[0].split(':')[1];
        var raw = window.atob(parts[1]);
        var rawLength = raw.length;
        var uInt8Array = new Uint8Array(rawLength);
        for (var i = 0; i < rawLength; ++i) {
            uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], { type: contentType });
    }

    /**
     * 下载
     */
    function downloadFile() {
        var aLink = document.createElement('a');
        // var blob = new Blob([content]);
        var blob = dataURItoBlob(imageDl);
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", false, false);//initEvent 不加后两个参数在FF下会报错
        aLink.download = guid();
        aLink.href = URL.createObjectURL(blob);
        aLink.dispatchEvent(evt);
    }

    /**
     * uuid
     * @returns {string}
     */
    function  guid() {
        return  'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' .replace(/[xy]/g,  function (c) {
            var  r = Math.random()*16|0, v = c ==  'x'  ? r : (r&0x3|0x8);
            return  v.toString(16);
        });
    }



</script>
